package com.atguigu.gulimall.auth.controller;

import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.utils.R;
import com.atguigu.gulimall.auth.feignService.MemberFeignService;
import com.atguigu.common.vo.MemberEntityVo;
import com.atguigu.gulimall.auth.vo.Social;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpSession;

@Slf4j
@Controller
public class OAuth2Controller {
    @Autowired
    MemberFeignService memberFeignService;
    @GetMapping("/oauth2.0/gitee/success")
    public String auth(@RequestParam(value = "code",required = false) String code, @RequestParam(value = "error",required = false) String error, HttpSession session){
        if (error!=null){
            return "redirect:http://auth.mall.com/login.html";
        }
        String client_id="f640bf9e53bc47753d864f254ec401e7335b939626343ed00a49173032b1d103";
        String grant_type = "authorization_code";
        String redirect_uri = "http://auth.mall.com/oauth2.0/gitee/success";
        String client_secret ="05a8886943277499f381464608e2a86ec5fc7e757a382676a646c936ad9ac39d";
        HttpResponse response = HttpUtil.createPost("https://gitee.com/oauth/token")
                .form("grant_type", grant_type)
                .form("code", code)
                .form("client_id", client_id)
                .form("redirect_uri", redirect_uri)
                .form("client_secret", client_secret)
                .execute();
       if (response.getStatus()==200){
           //获取到了token
           String josn = response.body().toString();
           Social social = JSON.parseObject(josn, new TypeReference<Social>() {});
           //使用token换用户信息、若是第一次登录自动注册，否则直接登录
           R login = memberFeignService.login(social);
           if (login.getCode()==0){
               MemberEntityVo data = login.getData("data",new TypeReference<MemberEntityVo>() {});
                log.info("登录成功{}",data);
                session.setAttribute("loginUser",data);

               return "redirect:http://mall.com";
           }else {
               return "redirect:http://auth.mall.com/login.html";
           }
       }else {
           return "redirect:http://auth.mall.com/login.html";
       }
    }
}
